<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/vhuichen.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/vhuichen.ico">
  <link rel="mask-icon" href="/vhuichen.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"vhuichen.github.io","root":"/","images":"/images","scheme":"Pisces","darkmode":false,"version":"8.13.0","exturl":false,"sidebar":{"position":"left","display":"display","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="需求用 Cookie 来实现自动登录的功能。 CookieCookie 是由服务器生成的，会在首次登陆或者重新登录时，通过 HTTP 的 Respone Header 发送给客户端。客户端一般会保存这个 Cookie 并在下一次访问该服务器时携带。服务器收到 Cookie 时会先判断 Cookie 是否有效，如果无效则提示客户端需要重新登录。   在 iOS 系统中，使用 NSURLRequest">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS Cookie 自动登录">
<meta property="og:url" content="https://vhuichen.github.io/2018/06/2018/06/iOS%20Cookie%20%E8%87%AA%E5%8A%A8%E7%99%BB%E5%BD%95/index.html">
<meta property="og:site_name" content="vhuichen">
<meta property="og:description" content="需求用 Cookie 来实现自动登录的功能。 CookieCookie 是由服务器生成的，会在首次登陆或者重新登录时，通过 HTTP 的 Respone Header 发送给客户端。客户端一般会保存这个 Cookie 并在下一次访问该服务器时携带。服务器收到 Cookie 时会先判断 Cookie 是否有效，如果无效则提示客户端需要重新登录。   在 iOS 系统中，使用 NSURLRequest">
<meta property="og:locale">
<meta property="article:published_time" content="2018-06-29T16:00:00.000Z">
<meta property="article:modified_time" content="2018-07-17T15:39:26.569Z">
<meta property="article:author" content="vhuichen">
<meta property="article:tag" content="Cookie">
<meta property="article:tag" content="NSHTTPCookieStorage">
<meta property="article:tag" content="NSHTTPCookie">
<meta property="article:tag" content="自动登录">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://vhuichen.github.io/2018/06/2018/06/iOS%20Cookie%20%E8%87%AA%E5%8A%A8%E7%99%BB%E5%BD%95/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-Hans","comments":true,"permalink":"https://vhuichen.github.io/2018/06/2018/06/iOS%20Cookie%20%E8%87%AA%E5%8A%A8%E7%99%BB%E5%BD%95/","path":"2018/06/2018/06/iOS Cookie 自动登录/","title":"iOS Cookie 自动登录"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>iOS Cookie 自动登录 | vhuichen</title>
  






  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">vhuichen</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录、分享</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section">Home</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">Archives</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section">About</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%9C%80%E6%B1%82"><span class="nav-number">1.</span> <span class="nav-text">需求</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Cookie"><span class="nav-number">1.1.</span> <span class="nav-text">Cookie</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#NSHTTPCookieStorage"><span class="nav-number">1.1.1.</span> <span class="nav-text">NSHTTPCookieStorage</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#NSHTTPCookie"><span class="nav-number">1.1.2.</span> <span class="nav-text">NSHTTPCookie</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B5%81%E7%A8%8B%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.2.</span> <span class="nav-text">流程实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#APP-%E9%80%80%E5%87%BA%E5%90%8E%EF%BC%8C%E7%B3%BB%E7%BB%9F%E8%87%AA%E5%8A%A8%E4%BF%9D%E5%AD%98-Cookie-%E7%9A%84%E5%89%8D%E6%8F%90%E6%9D%A1%E4%BB%B6"><span class="nav-number">1.3.</span> <span class="nav-text">APP 退出后，系统自动保存 Cookie 的前提条件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1%E3%80%81%E5%BF%85%E9%A1%BB%E7%A7%BB%E9%99%A4-NSHTTPCookieDiscard-%E8%BF%99%E4%B8%AA-key"><span class="nav-number">1.3.1.</span> <span class="nav-text">1、必须移除 NSHTTPCookieDiscard 这个 key</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2%E3%80%81%E5%BF%85%E9%A1%BB%E8%AE%BE%E7%BD%AE-NSHTTPCookieExpires-%E8%BF%99%E4%B8%AA-key%EF%BC%8C%E8%AE%BE%E7%BD%AE%E7%9A%84%E6%97%B6%E9%97%B4%E5%BF%85%E9%A1%BB%E5%A4%A7%E4%BA%8E%E5%BD%93%E5%89%8D%E7%B3%BB%E7%BB%9F%E6%97%B6%E9%97%B4"><span class="nav-number">1.3.2.</span> <span class="nav-text">2、必须设置 NSHTTPCookieExpires 这个 key，设置的时间必须大于当前系统时间</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%BB%93%E6%9D%9F"><span class="nav-number">2.</span> <span class="nav-text">结束</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="vhuichen"
      src="/images/vhuichen.jpg">
  <p class="site-author-name" itemprop="name">vhuichen</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">86</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="Back to top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://vhuichen.github.io/2018/06/2018/06/iOS%20Cookie%20%E8%87%AA%E5%8A%A8%E7%99%BB%E5%BD%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/vhuichen.jpg">
      <meta itemprop="name" content="vhuichen">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="vhuichen">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="iOS Cookie 自动登录 | vhuichen">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS Cookie 自动登录
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2018-06-30 00:00:00" itemprop="dateCreated datePublished" datetime="2018-06-30T00:00:00+08:00">2018-06-30</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">Edited on</span>
      <time title="Modified: 2018-07-17 23:39:26" itemprop="dateModified" datetime="2018-07-17T23:39:26+08:00">2018-07-17</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">In</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/iOS%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">iOS开发</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h2><p>用 Cookie 来实现自动登录的功能。</p>
<h3 id="Cookie"><a href="#Cookie" class="headerlink" title="Cookie"></a>Cookie</h3><p>Cookie 是由服务器生成的，会在首次登陆或者重新登录时，通过 HTTP 的 Respone Header 发送给客户端。客户端一般会保存这个 Cookie 并在下一次访问该服务器时携带。服务器收到 Cookie 时会先判断 Cookie 是否有效，如果无效则提示客户端需要重新登录。  </p>
<p>在 iOS 系统中，使用 NSURLRequest 的请求会默认加上 Cookie。同时也会默认保存以及更新 Cookie 。<br>Cookie 一般会在使用账号密码登陆时由服务器返回回来，下次登录时会根据这个 Cookie 来决定是否需要重新登录。登陆后每一次请求也会携带这个 Cookie ，用来判断是否有异地登录（Cookie 失效）。</p>
<blockquote>
<p>在 macOS 中的 Cookie 是共享的，而 iOS 中的 Cookie 则是单独使用的。</p>
</blockquote>
<p>iOS 对 Cookie 的相关操作主要有两个类。NSHTTPCookieStorage 和 NSHTTPCookie 。下面介绍下这两个类</p>
<span id="more"></span>

<h4 id="NSHTTPCookieStorage"><a href="#NSHTTPCookieStorage" class="headerlink" title="NSHTTPCookieStorage"></a>NSHTTPCookieStorage</h4><p>用来管理所有的 Cookie ，是个单例 。使用 NSURLRequest 请求返回的 Cookie 就是保存在这个类中。NSHTTPCookieStorage 默认的缓存策略是 NSHTTPCookieAcceptPolicyAlways ，也就是默认接受所有 Cookie 。<br>APP 运行时可以通过 NSHTTPCookieStorage 这个类获取到所有的 Cookie ，那么当 APP 退出关闭后，再重新打开还能不能从 NSHTTPCookieStorage 获取到上次使用的 Cookie 呢？答案是：能，但有条件限制，下面会讲到。  </p>
<h4 id="NSHTTPCookie"><a href="#NSHTTPCookie" class="headerlink" title="NSHTTPCookie"></a>NSHTTPCookie</h4><p>一个 NSHTTPCookie 对象只会保存一条 Cookie 信息。一般情况下 Cookie 都是服务器给的，有时候也可以手动创建一个</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSMutableDictionary</span> *properties = [<span class="built_in">NSMutableDictionary</span> dictionary];</span><br><span class="line">[properties setObject:<span class="string">@&quot;CookieName&quot;</span> forKey:<span class="built_in">NSHTTPCookieName</span>];</span><br><span class="line">[properties setObject:<span class="string">@&quot;134567890&quot;</span> forKey:<span class="built_in">NSHTTPCookieValue</span>];</span><br><span class="line">[properties setObject:<span class="string">@&quot;www.vhuichen.com&quot;</span> forKey:<span class="built_in">NSHTTPCookieDomain</span>];</span><br><span class="line">[properties setObject:<span class="string">@&quot;192.198.1.11&quot;</span> forKey:<span class="built_in">NSHTTPCookieOriginURL</span>];</span><br><span class="line">[properties setObject:<span class="string">@&quot;/&quot;</span> forKey:<span class="built_in">NSHTTPCookiePath</span>];</span><br><span class="line">[properties setObject:<span class="string">@&quot;0&quot;</span> forKey:<span class="built_in">NSHTTPCookieVersion</span>];</span><br><span class="line">[properties setObject:[<span class="built_in">NSDate</span> dateWithTimeIntervalSinceNow:<span class="number">8</span> * <span class="number">60</span> * <span class="number">60</span>] forKey:<span class="built_in">NSHTTPCookieExpires</span>];</span><br><span class="line"><span class="built_in">NSHTTPCookie</span> *cookie = [<span class="built_in">NSHTTPCookie</span> cookieWithProperties: properties];</span><br><span class="line">[[<span class="built_in">NSHTTPCookieStorage</span> sharedHTTPCookieStorage] setCookie:cookie];</span><br></pre></td></tr></table></figure>
<p>想要让 NSHTTPCookieStorage 保存手动设置的 Cookie，以便在下次启动是使用，这里也有一些限制条件，下面一起会讲到。</p>
<h3 id="流程实现"><a href="#流程实现" class="headerlink" title="流程实现"></a>流程实现</h3><p>我的做法是，当 APP 重启后，会先获取 NSHTTPCookieStorage 保存的 Cookie，如果有则尝试用 Cookie 直接登录，没有则进入登录页面。当用户主动退出登录时，则需要手动清除掉 NSHTTPCookieStorage 中保留的 Cookie 。</p>
<h3 id="APP-退出后，系统自动保存-Cookie-的前提条件"><a href="#APP-退出后，系统自动保存-Cookie-的前提条件" class="headerlink" title="APP 退出后，系统自动保存 Cookie 的前提条件"></a>APP 退出后，系统自动保存 Cookie 的前提条件</h3><p>要想 APP 退出后，系统自动保留 Cookie ，有两个前提条件。只要 Cookie 符合了 NSHTTPCookieStorage 的一些特定条件，NSHTTPCookieStorage 就会自动保存这个 Cookie ，在下次启动 APP 也就可以直接读出来使用。</p>
<h4 id="1、必须移除-NSHTTPCookieDiscard-这个-key"><a href="#1、必须移除-NSHTTPCookieDiscard-这个-key" class="headerlink" title="1、必须移除 NSHTTPCookieDiscard 这个 key"></a>1、必须移除 NSHTTPCookieDiscard 这个 key</h4><p>如果 Cookie 中保存有这个 key ，那么必须要移除这个 key ，否则系统不会自动保存。  </p>
<h4 id="2、必须设置-NSHTTPCookieExpires-这个-key，设置的时间必须大于当前系统时间"><a href="#2、必须设置-NSHTTPCookieExpires-这个-key，设置的时间必须大于当前系统时间" class="headerlink" title="2、必须设置 NSHTTPCookieExpires 这个 key，设置的时间必须大于当前系统时间"></a>2、必须设置 NSHTTPCookieExpires 这个 key，设置的时间必须大于当前系统时间</h4><p>只有设置了有效时间，并且有效时间大于当前时间，系统才会保存这个 Cookie 。一旦系统检测到保存的 Cookie 过时了（设置时间小于当前时间），就会直接删除 Cookie 。如果想长期保存 Cookie ，可以给这个 key 设置一个很大的时间。</p>
<h2 id="结束"><a href="#结束" class="headerlink" title="结束"></a>结束</h2><p>了解了 Cookie 的相关原理后，发现对 Cookie 的操作其实并不多。只需要在 APP 启动时获取 Cookie ，并在 APP 退出登录后，清空 Cookie 即可。</p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Cookie/" rel="tag"># Cookie</a>
              <a href="/tags/NSHTTPCookieStorage/" rel="tag"># NSHTTPCookieStorage</a>
              <a href="/tags/NSHTTPCookie/" rel="tag"># NSHTTPCookie</a>
              <a href="/tags/%E8%87%AA%E5%8A%A8%E7%99%BB%E5%BD%95/" rel="tag"># 自动登录</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2018/06/2018/06/NSPredicate%20%E7%94%A8%E6%B3%95/" rel="prev" title="NSPredicate用法">
                  <i class="fa fa-chevron-left"></i> NSPredicate用法
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2018/07/2018/07/iOS%E8%8E%B7%E5%8F%96%E7%B3%BB%E7%BB%9F%E6%97%B6%E5%8C%BA/" rel="next" title="iOS获取系统时区">
                  iOS获取系统时区 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2015 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">vhuichen</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/pisces/" rel="noopener" target="_blank">NexT.Pisces</a>
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
